package com.colin.videoservice.util;
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Configuration
public class VideoUtil {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    public static String bucketName;

    @Value("${aliyun.oss.endpoint}")
    public static String endpoint;

    // 常量定义，用于路径分类
    private static final String VIDEO_PREFIX = "videos/";
    private static final String COVER_PREFIX = "covers/";


    /**
     * 生成视频文件的对象键（命名规则）
     * 格式：videos/{userId}/{yyyy}/{MM}/{dd}/{videoTitle}_{uuid}_{timestamp}.{ext}
     */
    public static String generateVideoObjectKey(String originalFilename, String userId, String videoTitle) {
        // 获取文件扩展名
        String extension = getFileExtension(originalFilename);

        // 清理视频标题，移除特殊字符
        String cleanTitle = cleanFileName(videoTitle);

        // 生成UUID和时间戳
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        LocalDateTime now = LocalDateTime.now();
        String year = now.format(DateTimeFormatter.ofPattern("yyyy"));
        String month = now.format(DateTimeFormatter.ofPattern("MM"));
        String day = now.format(DateTimeFormatter.ofPattern("dd"));
        String timestamp = String.valueOf(System.currentTimeMillis());

        // 构建对象键
        return String.format(VIDEO_PREFIX + "%s/%s/%s/%s/%s_%s_%s%s",
                userId, year, month, day, cleanTitle, uuid, timestamp, extension);
    }


    public static String generateCoverObjectKey(String videoObjectKey, String coverExtension) {
        if (videoObjectKey == null || videoObjectKey.isEmpty()) {
            throw new IllegalArgumentException("视频对象键不能为空");
        }

        // 确保封面扩展名以点开头
        if (coverExtension != null && !coverExtension.startsWith(".")) {
            coverExtension = "." + coverExtension;
        }
        if (coverExtension == null || coverExtension.isEmpty()) {
            coverExtension = ".jpg"; // 默认封面格式
        }

        // 从视频对象键中提取路径信息，将 videos/ 替换为 covers/
        if (videoObjectKey.startsWith(VIDEO_PREFIX)) {
            String pathWithoutPrefix = videoObjectKey.substring(VIDEO_PREFIX.length());

            // 移除视频文件的原始扩展名，替换为封面扩展名
            int lastDotIndex = pathWithoutPrefix.lastIndexOf(".");
            if (lastDotIndex > 0) {
                pathWithoutPrefix = pathWithoutPrefix.substring(0, lastDotIndex);
            }

            return COVER_PREFIX + pathWithoutPrefix + coverExtension;
        }

        // 如果视频键不符合预期格式，生成基于时间的新键
        return generateDefaultCoverObjectKey(coverExtension);
    }

    /**
     * 生成默认格式的封面对象键（当无法从视频键推导时使用）
     */
    public static String generateDefaultCoverObjectKey(String extension) {
        if (extension == null || extension.isEmpty()) {
            extension = ".jpg";
        } else if (!extension.startsWith(".")) {
            extension = "." + extension;
        }

        LocalDateTime now = LocalDateTime.now();
        String year = now.format(DateTimeFormatter.ofPattern("yyyy"));
        String month = now.format(DateTimeFormatter.ofPattern("MM"));
        String day = now.format(DateTimeFormatter.ofPattern("dd"));
        String timestamp = String.valueOf(System.currentTimeMillis());
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

        return String.format(COVER_PREFIX + "shared/%s/%s/%s/cover_%s_%s%s",
                year, month, day, uuid, timestamp, extension);
    }

    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return ".mp4"; // 默认扩展名
        }
        return filename.substring(filename.lastIndexOf(".")).toLowerCase();
    }

    /**
     * 清理文件名，移除特殊字符
     */
    public static String cleanFileName(String filename) {
        if (filename == null) {
            return "video";
        }
        // 只保留字母、数字、中文、下划线和连字符
        return filename.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5_-]", "_");
    }

    /**
     * 验证视频文件类型
     */
    public static void validateVideoFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IOException("视频文件不能为空");
        }

        // 检查文件大小（限制为2GB）
        long maxSize = 2L * 1024 * 1024 * 1024; // 2GB
        if (file.getSize() > maxSize) {
            throw new IOException("视频文件大小不能超过2GB");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();

        if (contentType == null || !contentType.startsWith("video/")) {
            throw new IOException("只能上传视频文件");
        }

        // 检查文件扩展名
        if (filename != null) {
            String extension = getFileExtension(filename).toLowerCase();
            if (!isVideoExtension(extension)) {
                throw new IOException("不支持的视频格式: " + extension);
            }
        }
    }

    /**
     * 检查是否为支持的视频格式
     */
    public static boolean isVideoExtension(String extension) {
        String[] videoExtensions = {".mp4", ".avi", ".mov", ".wmv", ".flv", ".webm", ".mkv", ".m4v"};
        for (String videoExt : videoExtensions) {
            if (videoExt.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除视频文件
     */
    public boolean deleteVideo(String objectKey) {
        try {
            ossClient.deleteObject(bucketName, objectKey);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 删除封面文件
     */
    public boolean deleteCover(String coverObjectKey) {
        try {
            if (coverObjectKey != null && coverObjectKey.startsWith(COVER_PREFIX)) {
                ossClient.deleteObject(bucketName, coverObjectKey);
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
